package com.gc.web.controller.business;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.gc.business.domain.ElevatorInfo;
import com.gc.business.domain.UpkeepPlan;
import com.gc.business.domain.UpkeepTemplate;
import com.gc.business.service.IElevatorInfoService;
import com.gc.business.service.IUpkeepPlanService;
import com.gc.business.service.IUpkeepTemplateService;
import com.gc.common.annotation.Log;
import com.gc.common.base.Result;
import com.gc.common.enums.BusinessType;
import com.gc.common.json.JSONObject;
import com.gc.common.support.Convert;
import com.gc.common.utils.DateUtils;
import com.gc.common.utils.StringUtils;
import com.gc.common.utils.poi.ExcelUtil;
import com.gc.framework.util.ShiroUtils;
import com.gc.framework.web.base.BaseController;
import com.gc.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 电梯保养计划 控制层
 * 
 * @author hruiyan
 * @date 2020-11-19
 */
@Slf4j
@Controller
@RequestMapping("/business/upkeepPlan")
public class UpkeepPlanController extends BaseController {
    private String prefix = "business/upkeepPlan";

	@Autowired
	private ISysUserService userService;
	
	private final IUpkeepPlanService upkeepPlanService;
	private final IUpkeepTemplateService upkeepTemplateService;
	private final IElevatorInfoService elevatorInfoService;

	@Autowired
	public UpkeepPlanController(IUpkeepPlanService upkeepPlanService,
								IElevatorInfoService elevatorInfoService,
								IUpkeepTemplateService upkeepTemplateService) {
		this.upkeepPlanService = upkeepPlanService;
		this.elevatorInfoService = elevatorInfoService;
		this.upkeepTemplateService = upkeepTemplateService;
	}

	/**
	*  列表页
	*/
	@RequiresPermissions("business:upkeepPlan:view")
	@GetMapping
	public String upkeepPlan(ModelMap mmap,String selectMonth){
		//获取当年、当月
		String date = DateUtils.getDate();
		//传值改变
		if(StringUtils.isNotEmpty(selectMonth)){
			date = selectMonth;
		}
		String[] dateArray = date.split("-");
		List<JSONObject> json = this.getMonthList(Integer.parseInt(dateArray[0]), Integer.parseInt(dateArray[1]));
		mmap.put("fieldList", json.toString());
		return prefix + "/upkeepPlan";
	}

	/**
	 * 新增页
	 */
	@GetMapping("/add")
	public String add(){
		return prefix + "/add";
	}

	/**
	 * 编辑页
	 */
	@GetMapping("/edit/{planId}")
	public String edit(@PathVariable("planId") Long planId, ModelMap mmap){
		UpkeepPlan upkeepPlan = upkeepPlanService.selectUpkeepPlanListById(planId);
		//查询模板list
		List<UpkeepTemplate> templateList = upkeepTemplateService.list(new UpkeepTemplate(){{setCompanyId(ShiroUtils.getSysUser().getAttrId());}});
		mmap.put("upkeepPlan", upkeepPlan);
		mmap.put("templateList", templateList);
		return prefix + "/edit";
	}
	
	/**
	 * 查询电梯保养计划列表
	 */
	@RequiresPermissions("business:upkeepPlan:list")
	@PostMapping("/list")
	@ResponseBody
	public Result list(UpkeepPlan upkeepPlan){
		Long attrId = getAttrId();
		Boolean ifCompany = userService.ifCompanyRole(attrId);

		List<UpkeepPlan> list = new ArrayList<>();
		//公司角色查询
		if(ifCompany){
			upkeepPlan.setCompanyId(attrId);
			startPage();
			list = upkeepPlanService.selectUpkeepPlanList(upkeepPlan);
		}
		List<Map<String,Object>> mapList = new ArrayList<>();
		Map<String,Object> map = null;
		for (UpkeepPlan info : list) {
			map = new HashMap<>();
			map.put("elevatorInfo",info.getElevatorInfo());
			map.put("planId",info.getPlanId());
			//已保存间隔时间的
			if(info.getUpkeepInterval() != null){
				try {
					//计算保养日期
					Date dateTime = DateUtil.parse(info.getFirstUpkeepTime(),"yyyy-MM-dd");
					if(StringUtils.isNotEmpty(info.getRecentlyTime())){
						dateTime = DateUtil.parse(info.getRecentlyTime(),"yyyy-MM-dd");
					}
					long datelong = Long.valueOf(info.getUpkeepInterval());
					String date = DateUtils.getISO8601Time(DateUtils.getDate(dateTime, datelong));
					map.put(date,"√");
				}catch (Exception e){
					e.printStackTrace();
					return Result.failed();
				}
			}
			mapList.add(map);
		}
		return Result.success(getDataTable(mapList));
	}

	/**
	 * 新增保存电梯保养计划
	 */
	@RequiresPermissions("business:upkeepPlan:add")
	@Log(title = "电梯保养计划", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public Result addSave(UpkeepPlan upkeepPlan){
		upkeepPlanService.save(upkeepPlan);
		return Result.success();
	}

	/**
	 * 修改保存电梯保养计划
	 */
	@RequiresPermissions("business:upkeepPlan:edit")
	@Log(title = "电梯保养计划", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public Result editSave(UpkeepPlan upkeepPlan){
		upkeepPlanService.updateById(upkeepPlan);
		return Result.success();
	}
	
	/**
	 * 删除电梯保养计划
	 */
	@RequiresPermissions("business:upkeepPlan:remove")
	@Log(title = "电梯保养计划", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public Result remove(String ids){
		Long[] longIds = Convert.toLongArray(ids);
		upkeepPlanService.removeByIds(Arrays.asList(longIds));
		return Result.success();
	}

	/**
	 * 导出电梯保养计划列表
	 */
	@RequiresPermissions("business:upkeepPlan:export")
	@PostMapping("/export")
	@ResponseBody
	public Result export(UpkeepPlan upkeepPlan){
		List<UpkeepPlan> list = upkeepPlanService.list(upkeepPlan);
		ExcelUtil<UpkeepPlan> util = new ExcelUtil<>(UpkeepPlan.class);
		util.exportExcel(list, "upkeepPlan");
		return Result.success();
	}


	/**
	 * 获取每年每月表字段列
	 * @param year
	 * @param monthParam
	 * @return
	 */
	private List<JSONObject> getMonthList(int year,int monthParam){
		List<Map<String,Object>> monthList = DateUtils.getDayByMonth(year, monthParam);
		List<JSONObject> json = new ArrayList<>();
		JSONObject jsonData = null;
		//多选按钮
		jsonData = new JSONObject();
		jsonData.set("checkbox",true);
		json.add(jsonData);

		jsonData = new JSONObject();
		jsonData.set("field","planId");
		jsonData.set("title","ID");
		json.add(jsonData);

		jsonData = new JSONObject();
		jsonData.set("field","elevatorInfo.elevatorName");
		jsonData.set("title","电梯名称");
		json.add(jsonData);

		for(Map<String,Object> month : monthList){
			jsonData = new JSONObject();
			jsonData.set("field",month.get("aDate"));
			jsonData.set("title",month.get("aSky"));
			json.add(jsonData);
		}
		return json;
	}
}
